import express from "express";
import { ObjectId } from "mongodb";
import authMiddleware from "../middleware/auth.js";
import { getDb } from "../config/database.js";

const router = express.Router();
const COLLECTION = "transactions";

// 获取交易记录列表
router.get("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      page = 1,
      limit = 10,
      search = "",
      paymentMethod = "",
      payerId = "",
      payeeId = "",
    } = req.query;
    const skip = (Number(page) - 1) * Number(limit);

    // 构建查询条件
    const query = {};

    if (search) {
      query.$or = [
        { serialNumber: { $regex: search, $options: "i" } },
        { amount: { $regex: search, $options: "i" } },
      ];
    }

    if (paymentMethod) {
      query.paymentMethod = paymentMethod;
    }

    if (payerId) {
      query.payerId = payerId;
    }

    if (payeeId) {
      query.payeeId = payeeId;
    }

    // 查询数据
    const transactions = await db
      .collection(COLLECTION)
      .find(query)
      .sort({ transactionTime: -1 })
      .skip(skip)
      .limit(Number(limit))
      .toArray();

    // 获取总数
    const total = await db.collection(COLLECTION).countDocuments(query);

    res.json({
      transactions,
      total,
      page: Number(page),
      limit: Number(limit),
      totalPages: Math.ceil(total / Number(limit)),
    });
  } catch (error) {
    console.error("获取交易记录失败:", error);
    res.status(500).json({ error: "获取交易记录失败" });
  }
});

// 创建交易记录
router.post("/", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const {
      payerId,
      payeeId,
      transactionTime,
      amount,
      paymentMethod,
      confirmTime,
      serialNumber,
      relatedRecords,
    } = req.body;

    // 验证必填字段
    if (
      !payerId ||
      !payeeId ||
      !transactionTime ||
      !amount ||
      !paymentMethod ||
      !serialNumber
    ) {
      return res.status(400).json({ error: "所有必填字段都不能为空" });
    }

    // 获取付款方和收款方信息
    const [payerInfo, payeeInfo] = await Promise.all([
      getEntityInfo(db, payerId),
      getEntityInfo(db, payeeId),
    ]);

    if (!payerInfo || !payeeInfo) {
      return res.status(400).json({ error: "付款方或收款方不存在" });
    }

    // 创建新交易记录
    const newTransaction = {
      payerId,
      payeeId,
      payerName: payerInfo.name,
      payeeName: payeeInfo.name,
      transactionTime: new Date(transactionTime),
      amount: Number(amount),
      paymentMethod,
      confirmTime: confirmTime ? new Date(confirmTime) : null,
      serialNumber,
      relatedRecords: relatedRecords || [],
      createdAt: new Date(),
      updatedAt: new Date(),
    };

    const result = await db.collection(COLLECTION).insertOne(newTransaction);
    newTransaction._id = result.insertedId;

    res.status(201).json(newTransaction);
  } catch (error) {
    console.error("创建交易记录失败:", error);
    res.status(500).json({ error: "创建交易记录失败" });
  }
});

// 更新交易记录
router.put("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const { id } = req.params;
    const {
      payerId,
      payeeId,
      transactionTime,
      amount,
      paymentMethod,
      confirmTime,
      serialNumber,
      relatedRecords,
    } = req.body;

    // 验证必填字段
    if (
      !payerId ||
      !payeeId ||
      !transactionTime ||
      !amount ||
      !paymentMethod ||
      !serialNumber
    ) {
      return res.status(400).json({ error: "所有必填字段都不能为空" });
    }

    // 获取付款方和收款方信息
    const [payerInfo, payeeInfo] = await Promise.all([
      getEntityInfo(db, payerId),
      getEntityInfo(db, payeeId),
    ]);

    if (!payerInfo || !payeeInfo) {
      return res.status(400).json({ error: "付款方或收款方不存在" });
    }

    // 更新交易记录
    const updateData = {
      $set: {
        payerId,
        payeeId,
        payerName: payerInfo.name,
        payeeName: payeeInfo.name,
        transactionTime: new Date(transactionTime),
        amount: Number(amount),
        paymentMethod,
        confirmTime: confirmTime ? new Date(confirmTime) : null,
        serialNumber,
        relatedRecords: relatedRecords || [],
        updatedAt: new Date(),
      },
    };

    const result = await db
      .collection(COLLECTION)
      .findOneAndUpdate({ _id: new ObjectId(id) }, updateData, {
        returnDocument: "after",
      });

    if (!result) {
      return res.status(404).json({ error: "交易记录不存在" });
    }

    res.json(result);
  } catch (error) {
    console.error("更新交易记录失败:", error);
    res.status(500).json({ error: "更新交易记录失败" });
  }
});

// 获取单个交易记录
router.get("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const transaction = await db
      .collection(COLLECTION)
      .findOne({ _id: new ObjectId(req.params.id) });

    if (!transaction) {
      return res.status(404).json({ error: "交易记录不存在" });
    }

    res.json(transaction);
  } catch (error) {
    console.error("获取交易记录失败:", error);
    res.status(500).json({ error: "获取交易记录失败" });
  }
});

// 删除交易记录
router.delete("/:id", authMiddleware, async (req, res) => {
  try {
    const db = getDb();
    const result = await db
      .collection(COLLECTION)
      .findOneAndDelete({ _id: new ObjectId(req.params.id) });

    if (!result) {
      return res.status(404).json({ error: "交易记录不存在" });
    }

    res.json({ message: "交易记录删除成功" });
  } catch (error) {
    console.error("删除交易记录失败:", error);
    res.status(500).json({ error: "删除交易记录失败" });
  }
});

// 辅助函数：获取实体信息（客户或网点）
async function getEntityInfo(db, entityId) {
  if (entityId.startsWith("customer_")) {
    const customerId = entityId.replace("customer_", "");
    const customer = await db
      .collection("customers")
      .findOne({ _id: new ObjectId(customerId) });
    return customer
      ? {
          name: `${customer.name}${
            customer.alias ? `(${customer.alias})` : ""
          }`,
        }
      : null;
  } else if (entityId.startsWith("network_")) {
    const networkId = entityId.replace("network_", "");
    const network = await db
      .collection("networks")
      .findOne({ _id: new ObjectId(networkId) });
    return network
      ? { name: `${network.networkName}(${network.networkCode})` }
      : null;
  }
  return null;
}

export default router;
